package Utils;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 张
 * Date: 2025-01-22
 * Time: 17:11
 */
//需要封装和数据库之间的连接操作
public class DBUtil {
    private static final String URL = "jdbc:mysql://127.0.0.1:3306/oj_database?characterEncoding=utf8&useSSL=false";
    private static final String username = "root";
    private static final String password = "root";

    //单例模式
    private static volatile DataSource dataSource = null;

    private static DataSource getDataSource() {
        if(dataSource == null) { //提高效率,如果前面创建过了后续就无需进行加锁操作了
            synchronized (DBUtil.class) {
                if(dataSource == null) { //为了保证代码是实现单例的效果
                    MysqlDataSource mysqlDataSource = new MysqlDataSource();
                    mysqlDataSource.setUrl(URL);
                    mysqlDataSource.setUser(username);
                    mysqlDataSource.setPassword(password);
                    dataSource = mysqlDataSource;
                }
            }
        }
        return dataSource;//懒汉模式 -- 存在线程安全问题
    }

    public static Connection getConnection() throws SQLException {
        return getDataSource().getConnection();
    }

    //关闭释放连接
    public static void close(Connection connection, PreparedStatement statement, ResultSet resultSet) {
        if(resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
